﻿using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace System.Linq.Dynamic
{
    /// <summary>
    /// Enables the partial evalutation of queries. From http://msdn.microsoft.com/en-us/library/bb546158.aspx 
    /// </summary>
    internal class Evaluator
    {
        private static bool CanBeEvaluatedLocally(Expression expression)
        {
            return (expression.NodeType != ExpressionType.Parameter);
        }        

        public static Expression PartialEval(Expression expression)
        {
            return PartialEval(expression, new Func<Expression, bool>(Evaluator.CanBeEvaluatedLocally));
        }

        public static Expression PartialEval(Expression expression, out string listTag)
        {
            return PartialEval(expression, new Func<Expression, bool>(Evaluator.CanBeEvaluatedLocally), out listTag);
        }

        public static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated)
        {
            return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression);
        }

        public static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated, out string listTag)
        {
            Expression result = null;

            var subtreeEvaluator = new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression));

            result = subtreeEvaluator.Eval(expression);

            listTag = subtreeEvaluator.ListTag;

            return result;
        }

        public static string ToCacheString(Expression expression)
        {
            string result = null;

            var resultExpression = PartialEval(expression, new Func<Expression, bool>(Evaluator.CanBeEvaluatedLocally), out result);

            if (!string.IsNullOrEmpty(result))
            {
                result = string.Format("{0}|{1}", resultExpression.ToString(), result);
            }
            else
            {
                result = resultExpression.ToString();
            }

            return result;
        }

        // Nested Types
        private class Nominator : ExpressionVisitor
        {
            // Fields
            private HashSet<Expression> candidates;
            private bool cannotBeEvaluated;
            private Func<Expression, bool> fnCanBeEvaluated;

            // Methods
            internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
            {
                this.fnCanBeEvaluated = fnCanBeEvaluated;
            }

            internal HashSet<Expression> Nominate(Expression expression)
            {
                this.candidates = new HashSet<Expression>();
                this.Visit(expression);
                return this.candidates;
            }

            protected override Expression Visit(Expression expression)
            {
                if (expression != null)
                {
                    bool cannotBeEvaluated = this.cannotBeEvaluated;
                    this.cannotBeEvaluated = false;
                    base.Visit(expression);
                    if (!this.cannotBeEvaluated)
                    {
                        if (this.fnCanBeEvaluated(expression))
                        {
                            this.candidates.Add(expression);
                        }
                        else
                        {
                            this.cannotBeEvaluated = true;
                        }
                    }
                    this.cannotBeEvaluated |= cannotBeEvaluated;
                }
                return expression;
            }
        }

        private class SubtreeEvaluator : ExpressionVisitor
        {
            // Fields
            private HashSet<Expression> candidates;
            private string listTag = string.Empty;

            // Properties
            public string ListTag
            {
                get 
                { 
                    return listTag; 
                }
            }

            // Methods
            internal SubtreeEvaluator(HashSet<Expression> candidates)
            {
                this.candidates = candidates;
            }

            internal Expression Eval(Expression exp)
            {
                return this.Visit(exp);
            }

            private Expression Evaluate(Expression e)
            {
                ConstantExpression result;

                if (e.NodeType == ExpressionType.Constant)
                {
                    result = e as ConstantExpression;
                }
                else
                {
                    result = Expression.Constant(Expression.Lambda(e, new ParameterExpression[0]).Compile().DynamicInvoke(null), e.Type);

                    var enumerable = result.Value as IEnumerable;

                    if (enumerable != null)
                    {
                        listTag = string.Format("{0}{1}|", 
                            listTag, 
                            enumerable is string ? 
                                enumerable : 
                                GetValuesSeperated(enumerable));
                    }
                }

                return result;
            }

            protected override Expression Visit(Expression exp)
            {
                if (exp == null)
                {
                    return null;
                }
                if (this.candidates.Contains(exp))
                {
                    return this.Evaluate(exp);
                }
                return base.Visit(exp);
            }

            /// <summary>
            /// Get aggregated string consisted of sequence elements 
            /// </summary>
            public static string GetValuesSeperated(IEnumerable enumerable)
            {
                IEnumerator en = enumerable.GetEnumerator();

                StringBuilder sb = new StringBuilder();

                if (en.MoveNext())
                {
                    sb.Append(en.Current.ToString());
                }

                while (en.MoveNext())
                {
                    sb.AppendFormat(";{0}", en.Current);
                }

                return sb.ToString();
            }
        }
    }
}
